import os
import django
from pymodbus.client import ModbusTcpClient

from index.db_Session import get_db_session
from basic_db_ops2 import *
from index import views
from basic_db_ops import *
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject1.settings')
django.setup()



#用来测试能否将光伏数据正常写入数据库
import time
# postgres_user_name = "postgres"
# password = "123456"
# db_name = "system_database"
# engine = create_engine(f'postgresql://{postgres_user_name}:{password}@localhost:5432/{db_name}')
# Session = sessionmaker(bind=engine) # 生成 Session 类
# # 控制循环的开关
# running = True
# try:
#     while running:
#         # 记录本次循环开始时间
#         start_time = time.time()
#         # 调用你的函数
#         write_inverter_second_data1(Session, 1)
#         # 计算剩余等待时间（1秒 - 函数执行时间）
#         elapsed = time.time() - start_time
#         sleep_time = max(0.0, 1.0 - elapsed)  # 避免负数
#         # 精确等待剩余时间
#         time.sleep(sleep_time)
# except KeyboardInterrupt:
#     print("\n循环已手动停止")
#     running = False
#
# print(type(views.api_bs_info))

if __name__ == '__main__':
    # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject1.settings')
    # django.setup()
    # print("hello")

    # Session = get_db_session()
    # 配置 Modbus 连接
    # 定义 Modbus 服务器的 IP 地址
    MODBUS_SERVER_IP = "127.0.0.1"
    # 定义 Modbus 服务器的端口号
    MODBUS_SERVER_PORT = 1502
    # 定义 Modbus 从站的 ID
    SLAVE_ID = 1

    # from pymodbus.client.sync import ModbusTcpClient

    # 连接到 Modbus TCP 服务器
    client = ModbusTcpClient(host=MODBUS_SERVER_IP, port=MODBUS_SERVER_PORT)
    if client.connect():
        # 读取保持寄存器的值
        result = client.read_holding_registers(address=1, count=10)
        if not result.isError():
            print('Read holding registers:', result.registers)
        else:
            print('Error reading holding registers:', result)
        # 关闭连接
        client.close()
    else:
        print('Could not connect to Modbus TCP server')

    import os
    import django

    # 设置 DJANGO_SETTINGS_MODULE 环境变量
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject1.settings')

    # 初始化 Django
    django.setup()

    print("HELLO")